package com.yt.demo.controller;

import com.yt.demo.dao.UserDao;
import com.yt.demo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@Slf4j
public class ShiroUserLoginController {
    @RequestMapping("/login")
    public String login(User user) {
        return "login";
    }

    //    @ResponseBody
    @RequestMapping("/shiro/login")
    public String shirologin(User user,
                             @RequestParam(defaultValue = "false") boolean rememberMe,
                             HttpSession session) {
        log.info("rememberMe   =========>>>>>>> "+rememberMe);
        String info = "登录失败";
        log.info("loginuser:" + user);
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken token =
                new UsernamePasswordToken(user.getUsername(), user.getPassword(),rememberMe);
        try {
            subject.login(token);
            session.setAttribute("cuser",(User)subject.getPrincipal());
            log.info("登录成功。。。。。。");
            return "index";
        } catch (UnknownAccountException uae) {
            log.error("UnknownAccountException", uae);
            session.setAttribute("errorMessage", "用户不存在");
        } catch (IncorrectCredentialsException ice) {
            log.error("IncorrectCredentialsException", ice);
            session.setAttribute("errorMessage", "密码错误");
        } catch (AuthenticationException e) {
            log.error("登录error", e);
            session.setAttribute("errorMessage", "AuthenticationException");
        }
        return "login";
    }

    @RequestMapping("/success")
    public String rememberMelogin(HttpSession session){
        session.setAttribute("cuser","rememberMe");
        return "index";
    }
//    @RequestMapping("/logout")
//    public String logout(HttpSession session){
//        Subject subject = SecurityUtils.getSubject();
//        subject.logout();
//        return "login";
//    }
}
